package petrochina.company.electric.ui.fragment;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.WrapRecyclerView;
import com.inuker.bluetooth.library.search.SearchResult;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import petrochina.company.electric.R;
import petrochina.company.electric.app.AppActivity;
import petrochina.company.electric.app.TitleBarFragment;
import petrochina.company.electric.event.ManagerConfirmEvent;
import petrochina.company.electric.event.ManagerLogoutTipEvent;
import petrochina.company.electric.event.SendManagerWorkEvent;
import petrochina.company.electric.event.TaskStepStatusChangeEvent;
import petrochina.company.electric.http.api.BleDeviceListApi;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.api.TaskDetailStepApi;
import petrochina.company.electric.http.api.TaskListApi;
import petrochina.company.electric.http.api.TaskSubmitApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.model.ArtificialRequestData;
import petrochina.company.electric.model.TaskStepInfo;
import petrochina.company.electric.other.PermissionCallback;
import petrochina.company.electric.service.TaskWebSocketService;
import petrochina.company.electric.ui.adapter.TaskDetailAdapter;
import petrochina.company.electric.ui.dialog.BleDeviceOptionDialog;
import petrochina.company.electric.ui.dialog.BleDeviceSearchDialog;
import petrochina.company.electric.ui.dialog.BleLockOptionMenuDialog;
import petrochina.company.electric.ui.dialog.BleLockSearchMenuDialog;
import petrochina.company.electric.ui.dialog.TaskBackgroundConfirmDialog;
import petrochina.company.electric.ui.dialog.TaskCustomerConfirmDialog;
import petrochina.company.electric.utils.DateUtil;

/**
 * desc   : 停电 复电 Fragment
 * type: 0 停电 1复电
 */
public final class PowerFragment extends TitleBarFragment<AppActivity>
        implements OnRefreshLoadMoreListener,
        BaseAdapter.OnChildClickListener {
    private static final String INTENT_KEY_IN_TYPE = "type";
    private static final String INTENT_KEY_IN_CODE = "code";
    /**
     * 0 停电 1复电
     */
    private int powerType = 0;
    private TaskListApi.Bean mTaskResult;

    public static PowerFragment newInstance(int type, String taskResult) {
        PowerFragment fragment = new PowerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(INTENT_KEY_IN_TYPE, type);
        bundle.putString(INTENT_KEY_IN_CODE, taskResult);
        fragment.setArguments(bundle);
        return fragment;
    }

    TaskWebSocketService webSocketService;
    private MMKV mmkv;
    private Gson gson;
    private LoginApi.Bean loginBean;
    private SmartRefreshLayout mRefreshLayout;
    private WrapRecyclerView mRecyclerView;

    private TaskDetailAdapter mTaskAdapter;

    private List<TaskStepInfo> stepList;

    private AlertDialog alertDialog;

    private Handler mHandle = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Log.d("PowerFragmentApi", "开始轮询接口");
                getListData();
            }
        }
    };


    /**
     * 当前执行任务
     */
    private TaskDetailStepApi.Bean currentExciteTask;

    TaskCustomerConfirmDialog.Builder mTaskCustomerConfirmBuilder;
    TaskBackgroundConfirmDialog.Builder mTaskBackgroundConfirmBuilder;
    BleLockSearchMenuDialog.Builder mBleLockSearchBuilder;
    BleDeviceSearchDialog.Builder mBlDevicesSearchBuilder;

    private BluetoothAdapter bluetoothAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.power_fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();
        String jsonStr = mmkv.getString("loginData", null);
        if (!TextUtils.isEmpty(jsonStr)) {
            loginBean = gson.fromJson(jsonStr, LoginApi.Bean.class);
        }
        mRefreshLayout = findViewById(R.id.rl_task_power_refresh);
        mRecyclerView = findViewById(R.id.rv_task_power_list);
        powerType = getInt(INTENT_KEY_IN_TYPE);
        String resultStr = getString(INTENT_KEY_IN_CODE);
        if (!TextUtils.isEmpty(resultStr)) {
            mTaskResult = gson.fromJson(resultStr, TaskListApi.Bean.class);
        }

        int userType = 0;
        if (loginBean != null) {
            userType = loginBean.getDutyType();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setCancelable(true); // if you want user to wait for some process to finish,
        builder.setView(R.layout.layout_loading_dialog);
        alertDialog = builder.create();

        mTaskAdapter = new TaskDetailAdapter(getAttachActivity(), userType);
        mTaskAdapter.setOnChildClickListener(R.id.ll_task_execute, this);
        mTaskAdapter.setOnChildClickListener(R.id.ll_task_help, this);
        mRecyclerView.setAdapter(mTaskAdapter);
//        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableLoadMore(false);
//        requireContext().bindService(new Intent(requireActivity(), TaskWebSocketService.class), serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void initData() {
        stepList = new ArrayList<>();
        getListData();
    }

    public void getListData() {
        EasyHttp.get(this)
                .api(new TaskDetailStepApi().setCode(mTaskResult.getId()).setType(powerType))
                .request(new HttpCallback<HttpData<List<TaskDetailStepApi.Bean>>>(this) {

                    @Override
                    public void onSucceed(HttpData<List<TaskDetailStepApi.Bean>> result) {
                        if (loginBean.getDutyType() != 1) {
                            for (TaskDetailStepApi.Bean data : result.getData()) {
//                                TaskStepInfo info = new TaskStepInfo(data.getId(), 0, 0, 0);
                                if (data.getStatus() == 0) {
                                    // 第一个未完成的步骤设置为进行中
                                    data.setStatus(1);
                                    break;
                                } else if (data.getStatus() == 1) {
                                    break;
                                }
                            }
                        }
                        mTaskAdapter.setData(result.getData());
                        mRefreshLayout.finishRefresh();

                        // 监管账号，10秒轮询一次接口
                        if (loginBean.getDutyType() == 1) {
                            mHandle.sendEmptyMessageDelayed(1, 5 * 1000);
                        }
                    }
                });
    }

    public void refreshData(int position) {
        onRefresh(null);
    }

    /**
     * {@link OnRefreshLoadMoreListener}
     */

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            mTaskAdapter.clearData();
            getListData();
        }, 1000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            EasyHttp.get(this)
                    .api(new TaskDetailStepApi().setCode(mTaskResult.getId()).setType(powerType))
                    .request(new HttpCallback<HttpData<List<TaskDetailStepApi.Bean>>>(this) {

                        @Override
                        public void onSucceed(HttpData<List<TaskDetailStepApi.Bean>> result) {
//                            for (TaskDetailStepApi.Bean data : result.getData()) {
//                                if (data.getStepStatus() == 0) {
//                                    // 第一个未完成的步骤设置为进行中
//                                    data.setStepStatus(1);
//                                    break;
//                                }
//                            }
//                            mTaskAdapter.setData(result.getData());
                            mRefreshLayout.finishLoadMore();
                        }
                    });
            mRefreshLayout.finishLoadMore();
            mTaskAdapter.setLastPage(mTaskAdapter.getCount() >= 100);
            mRefreshLayout.setNoMoreData(mTaskAdapter.isLastPage());
        }, 1000);
    }

    /**
     * *
     * * @param recyclerView RecyclerView对象
     * * @param itemChildView     被点击的条目对象 子View
     * * @param position     被点击的条目位置
     */
    @Override
    public void onChildClick(RecyclerView recyclerView, View childView, int position) {
        // 只有进行中的步骤才可点击执行
        if (childView.getId() == R.id.ll_task_execute) {
            if (mTaskAdapter.getItem(position).getStatus() == 1) {
                currentExciteTask = mTaskAdapter.getItem(position);
                this.requestPermission();
            }
        } else if (childView.getId() == R.id.ll_task_help) {
            currentExciteTask = mTaskAdapter.getItem(position);
            ArtificialRequestData data = new ArtificialRequestData(mTaskResult, mTaskAdapter.getItem(position), loginBean, DateUtil.getNowTime());
            String dataStr = gson.toJson(data);
            SendManagerWorkEvent event = new SendManagerWorkEvent(1, loginBean.getId(), mTaskResult.getCheckStaffId(), dataStr);
            EventBus.getDefault().post(event);
            alertDialog.show();
//            ToastUtils.show("点击人工");

        }
    }

    private void requestPermission() {
        XXPermissions.with(getAttachActivity())
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new PermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            checkBlueStatus();
                        } else {
                            showRequestPermissionDialog();
                        }
                    }
                });
    }

    /**
     * 设置权限对话框
     */
    private void showRequestPermissionDialog() {
        new BaseDialog.Builder<>(getAttachActivity())
                .setGravity(Gravity.BOTTOM)
                .setContentView(R.layout.permission_dialog)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                //.setText(id, "我是预设置的文本")
                .setOnClickListener(R.id.btn_dialog_custom_ok, (BaseDialog.OnClickListener<Button>) (dialog, button) -> {
                    dialog.dismiss();
                    this.requestPermission();
                })
                .setOnCreateListener(dialog -> toast("Dialog 创建了"))
                .addOnShowListener(dialog -> toast("Dialog 显示了"))
                .addOnCancelListener(dialog -> toast("Dialog 取消了"))
                .show();
    }

    private void checkBlueStatus() {
        if (!isSupportBle(getContext())) {
            toast("手机不支持Ble蓝牙设备");
            return;
        }
        if (!isBleEnable()) {
            turnOnBlueToothNo();
            toast("请重新执行搜索蓝牙设备");
        } else {
            checkGpsStatus();
        }
    }

    /**
     * 强制打开蓝牙（不弹出系统弹出框）
     */
    public void turnOnBlueToothNo() {
        if (!isBleEnable()) {
            if (bluetoothAdapter != null) {
                bluetoothAdapter.enable();
            }
        }
    }

    public boolean isBleEnable() {
        BluetoothAdapter bluetoothAdapter = getBluetoothAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

    public boolean isSupportBle(Context context) {
        return (getBluetoothAdapter() != null && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE));
    }

    private BluetoothAdapter getBluetoothAdapter() {
        if (bluetoothAdapter == null) {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        return bluetoothAdapter;
    }


    private void checkGpsStatus() {
        if (!isGpsOpen(getAttachActivity())) {
            new AlertDialog.Builder(getAttachActivity())
                    .setTitle("提示")
                    .setMessage("为了更精确的扫描到Bluetooth LE设备,请打开GPS定位")
                    .setPositiveButton("确定", (dialog, which) -> {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, (resultCode, data) -> {
                            this.checkGpsStatus();
                        });
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        } else {
            showTaskListDialog();
        }
    }

    /**
     * 设备类型（0：其它1：开关 2：验电棒 3：接地极 4：锁具）
     */
    private void showTaskListDialog() {
        int taskType = currentExciteTask.getEquipType();
        // 上报执行操作统计
        uploadAction(1, 0);
        switch (taskType) {
            case 0:
                showCustomerConfirm();
                break;
            case 1:
                showBackgroundConfirm();
                break;
            case 2:
                showBleDevicesSearch();
//                showBackgroundConfirm();
                break;
            case 3:
                showBleDevicesSearch();
//                showBackgroundConfirm();
                break;
            case 4:
                showBleLockSearch();
                break;
        }

    }

    /**
     * 记录动作（执行、比对失败）
     */
    private void uploadAction(int stepStatus, int stepEquipValue) {
        if (mTaskAdapter.getData() != null && stepList != null) {
            TaskStepInfo stepInfo = new TaskStepInfo(currentExciteTask.getId(), stepStatus, stepEquipValue, stepStatus == 1 ? 0 : currentExciteTask.getOperType(), 1);
            Gson gson = new Gson();
            String stepDataStr = gson.toJson(stepInfo);

            EasyHttp.post(this)
                    .api(new TaskSubmitApi())
                    .json(stepDataStr)
                    .request(new HttpCallback<HttpData<TaskSubmitApi.Bean>>(this) {

                        @Override
                        public void onSucceed(HttpData<TaskSubmitApi.Bean> result) {
                            if (stepStatus == 1) {

                            }
//                            int index = mTaskAdapter.getData().indexOf(currentExciteTask);
//                            mTaskAdapter.getData().get(index).setStatus(3);
//                            for (int i = index + 1; i < mTaskAdapter.getCount(); i++) {
//                                if (mTaskAdapter.getData().get(i).getStatus() == 0) {
//                                    mTaskAdapter.getData().get(i).setStatus(1);
//                                    break;
//                                }
//                            }
//                            mTaskAdapter.notifyDataSetChanged();
//                            requireActivity().finish();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            ToastUtils.show("提交失败");
                        }
                    });

        }
    }

    public static boolean isGpsOpen(Context context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    /**
     * 本地保存提交记录，最后一步统一提交
     *
     * @param stepEquipValue
     */
    private void saveStepInfo(int stepEquipValue, int operIdentifyType) {
        if (mTaskAdapter.getData() != null && stepList != null) {
            TaskStepInfo stepInfo = new TaskStepInfo(currentExciteTask.getId(), 3, stepEquipValue, currentExciteTask.getOperType(), operIdentifyType);
            // 改为每个步骤提交一次
            Gson gson = new Gson();
            String stepDataStr = gson.toJson(stepInfo);

            EasyHttp.post(this)
                    .api(new TaskSubmitApi())
                    .json(stepDataStr)
                    .request(new HttpCallback<HttpData<TaskSubmitApi.Bean>>(this) {

                        @Override
                        public void onSucceed(HttpData<TaskSubmitApi.Bean> result) {
                            int index = mTaskAdapter.getData().indexOf(currentExciteTask);
                            mTaskAdapter.getData().get(index).setStatus(3);
                            for (int i = index + 1; i < mTaskAdapter.getCount(); i++) {
                                if (mTaskAdapter.getData().get(i).getStatus() == 0) {
                                    mTaskAdapter.getData().get(i).setStatus(1);
                                    // 完成最后一个刷新任务列表数据
                                    if (i == mTaskAdapter.getCount() - 1) {
                                        TaskStepStatusChangeEvent event = new TaskStepStatusChangeEvent(1);
                                        EventBus.getDefault().post(event);
                                    }
                                    break;
                                }
                            }
                            mTaskAdapter.notifyDataSetChanged();
//                            requireActivity().finish();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            ToastUtils.show("提交失败");
                        }
                    });

//            if (stepList.size() == mTaskAdapter.getCount()) {
//                TaskStepData data = new TaskStepData(stepList);
//                Gson gson = new Gson();
//                String stepDataStr = gson.toJson(data);
//                submitTaskStep(stepDataStr);
//            }
        }
    }

    /**
     * 提交任务
     *
     * @param stepDataStr
     */
    private void submitTaskStep(String stepDataStr) {

    }

    /**
     * 人工确认
     */
    private void showCustomerConfirm() {
        // 蓝牙锁弹框
        mTaskCustomerConfirmBuilder = new TaskCustomerConfirmDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setGravity(Gravity.BOTTOM)
                .setListener(new TaskCustomerConfirmDialog.OnListener<SearchResult>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, SearchResult bleDevice) {
                        saveStepInfo(0, 1);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                });
        mTaskCustomerConfirmBuilder.show();
    }

    /**
     * 后台确认
     */
    private void showBackgroundConfirm() {
        // 蓝牙锁弹框
        mTaskBackgroundConfirmBuilder = new TaskBackgroundConfirmDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setGravity(Gravity.BOTTOM)
                .setData(currentExciteTask)
                .setType(powerType)
                .setAutoDismiss(false)
                .setListener(new TaskBackgroundConfirmDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        if (position == 0) {
                            saveStepInfo(0, 1);
                            dialog.dismiss();
                        } else {
                            // 比对失败上传统计
                            uploadAction(2, 0);
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                });
        mTaskBackgroundConfirmBuilder.show();

    }

    /**
     * 搜索 蓝牙设备 连接
     * 当前任务 传递进去 进行搜索匹配 展示
     */
    private void showBleDevicesSearch() {
        // 蓝牙锁弹框
        mBlDevicesSearchBuilder = new BleDeviceSearchDialog.Builder(getContext(), currentExciteTask.getEquipType())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setGravity(Gravity.BOTTOM)
                .setData(currentExciteTask)
                .setListener(new BleDeviceSearchDialog.OnListener<BleDeviceListApi.Bean>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, BleDeviceListApi.Bean bleDevice) {
//                        toast("位置：" + position + "，设备名称：" + bleDevice.getName());
                        dialog.hide();
                        showBleDevicesOption(bleDevice);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                });
        mBlDevicesSearchBuilder.show();
    }

    /**
     * 搜索 优特蓝牙锁 连接
     * 当前任务 传递进去 进行搜索匹配 展示
     */
    private void showBleLockSearch() {
        // 蓝牙锁弹框
        mBleLockSearchBuilder = new BleLockSearchMenuDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setGravity(Gravity.BOTTOM)
                .setListener(new BleLockSearchMenuDialog.OnListener<BleDeviceListApi.Bean>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, BleDeviceListApi.Bean bleDevice) {
//                        toast("位置：" + position + "，设备名称：" + bleDevice.getName());
                        dialog.hide();
                        showBleLockOption(bleDevice);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        toast("取消了");
                    }
                });
        mBleLockSearchBuilder.show();
    }

    /**
     * 蓝牙设备连接使用
     */
    private void showBleDevicesOption(BleDeviceListApi.Bean bleDevice) {
        // 蓝牙锁弹框
        new BleDeviceOptionDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                // 设置点击按钮后不关闭对话框
                .setGravity(Gravity.BOTTOM)
                .setBleDevice(bleDevice)
                .setData(currentExciteTask)
                .setAutoDismiss(false)
                .setListener(new BleDeviceOptionDialog.OnListener<Integer>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, Integer stepStatus) {
                        if (position == 0) {
                            saveStepInfo(stepStatus, 1);
                            dialog.dismiss();
                            mBlDevicesSearchBuilder.dismiss();
                        } else {
                            uploadAction(2, stepStatus);
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                        mBlDevicesSearchBuilder.dismiss();
                    }
                })
                .show();

    }

    /**
     * 蓝牙锁连接使用
     */
    private void showBleLockOption(BleDeviceListApi.Bean bleDevice) {
        // 蓝牙锁弹框
        new BleLockOptionMenuDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setGravity(Gravity.BOTTOM)
                .setBleDevice(bleDevice)
                .setData(currentExciteTask)
                .setAutoDismiss(false)
                .setListener(new BleLockOptionMenuDialog.OnListener<Integer>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, Integer stepStatus) {
                        if (position == 0) {
                            saveStepInfo(0, 1);
                            dialog.dismiss();
                            mBleLockSearchBuilder.dismiss();
                        } else {
                            uploadAction(2, 0);
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                        mBleLockSearchBuilder.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandle.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
//        requireActivity().unbindService(serviceConnection);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ManagerLogoutTipEvent event) {
        if (event != null) {
            ToastUtils.show(event.getData());
            alertDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ManagerConfirmEvent event) {
        if (event != null) {
            if (event.getType() == 3) {
                // 人工确认通过
                ToastUtils.show("人工确认已通过");
                saveStepInfo(0, 2);
//                ToastUtils.show("人工确认通过，提交任务步骤");
            } else {
                // 人工确认不通过
                ToastUtils.show("人工确认被驳回");
            }
            alertDialog.dismiss();
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(TaskStepStatusChangeEvent event) {
//        if (event != null) {
//            String dataJson = event.getData();
//            if (!TextUtils.isEmpty(dataJson)) {
//                ArtificialRequestData data = null;
//                try {
//                    data = gson.fromJson(dataJson, ArtificialRequestData.class);
//                } catch (Exception e) {
//
//                }
//                if (data != null && data.getLogin() != null && data.getDetail() != null) {
//                    if (mTaskAdapter != null && mTaskAdapter.getData() != null && mTaskAdapter.getCount() > 0) {
//                        int index = mTaskAdapter.getData().indexOf(data.getDetail());
//                        if (index != -1) {
//                            mTaskAdapter.setItem(index, data.getDetail());
//                        }
//                    }
//                }
//            }
//        }
//    }

//    private ServiceConnection serviceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            webSocketService = ((TaskWebSocketService.LocalBinder) service).getService();
//            webSocketService.setWebSocketCallback(webSocketCallback);
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            webSocketService = null;
//        }
//    };
//
//    private TaskWebSocketService.WebSocketCallback webSocketCallback = new TaskWebSocketService.WebSocketCallback() {
//        @Override
//        public void onMessage(final String text) {
//            requireActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    ToastUtils.show(text);
////                    tvMessage.setText(text);
//                }
//            });
//        }
//
//        @Override
//        public void onOpen() {
//            requireActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    String dataJson = mmkv.getString("loginData", null);
//                    if (!TextUtils.isEmpty(dataJson)) {
//                        LoginApi.Bean bean = gson.fromJson(dataJson, LoginApi.Bean.class);
//                        if (bean!= null && bean.getId()!= 0 && webSocketService != null){
//                            SocketMessageData data = new SocketMessageData(0, bean.getId(),0,"");
//                            String json = gson.toJson(data);
//                            webSocketService.send(json);
//                        }
//                    }
//                }
//            });
//        }
//
//        @Override
//        public void onClosed() {
//            requireActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    ToastUtils.show("onClosed");
//                }
//            });
//        }
//    };
}